import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../model/book.dart';
import '../service/book_provider.dart';

class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  List<Book> _searchResults = [];
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    Provider.of<BookProvider>(context, listen: false).fetchBooks();
  }

  @override
  Widget build(BuildContext context) {
    final bookProvider = Provider.of<BookProvider>(context);

    if (bookProvider.isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    if (bookProvider.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('加载失败: ${bookProvider.error}'),
            ElevatedButton(
              onPressed: bookProvider.fetchBooks,
              child: Text('重试'),
            ),
          ],
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('查询图书'),
      ),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(8),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                labelText: '搜索',
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: _performSearch,
                ),
              ),
              onSubmitted: (_) => _performSearch(),
            ),
          ),
          _isSearching
              ? Center(child: CircularProgressIndicator())
              : Expanded(
                  child: _searchResults.isNotEmpty
                      ? ListView.builder(
                          itemCount: _searchResults.length,
                          itemBuilder: (context, index) {
                            final book = _searchResults[index];
                            return ListTile(
                              leading: book.coverUrl != null
                                  ? Image.network(book.coverUrl!, width: 50)
                                  : Icon(Icons.book, size: 50),
                              title: Text(book.title),
                              subtitle: Text(book.author),
                              onTap: () => _showBookDetails(book),
                            );
                          },
                        )
                      : Center(
                          child: Text(
                            bookProvider.books.isEmpty
                                ? '暂无图书数据'
                                : '输入关键词搜索图书',
                          ),
                        ),
                ),
        ],
      ),
    );
  }

  void _performSearch() {
    final query = _searchController.text.trim().toLowerCase();
    if (query.isEmpty) return;

    setState(() {
      _isSearching = true;
    });

    final bookProvider = Provider.of<BookProvider>(context, listen: false);
    _searchResults = bookProvider.books.where((book) {
      return book.title.toLowerCase().contains(query) ||
          book.author.toLowerCase().contains(query) ||
          book.isbn.toLowerCase().contains(query) ||
          (book.publisher != null &&
              book.publisher!.toLowerCase().contains(query));
    }).toList();

    setState(() {
      _isSearching = false;
    });
  }

  void _showBookDetails(Book book) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(book.title),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              if (book.coverUrl != null)
                Center(child: Image.network(book.coverUrl!)),
              SizedBox(height: 10),
              Text('ISBN: ${book.isbn}'),
              Text('作者: ${book.author}'),
              if (book.publisher != null) Text('出版社: ${book.publisher}'),
              if (book.publishDate != null)
                Text('出版日期: ${book.publishDate}'),
              if (book.pageCount != null) Text('页数: ${book.pageCount}'),
              if (book.description != null)
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Text('简介: ${book.description}'),
                ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}